package cn.accjiyun.controller.article;

import cn.accjiyun.core.controller.BaseController;
import cn.accjiyun.core.entity.PageModel;
import cn.accjiyun.core.utils.WebUtils;
import cn.accjiyun.model.article.Article;
import cn.accjiyun.model.article.ArticleContent;
import cn.accjiyun.model.article.QueryArticle;
import cn.accjiyun.service.ArticleService;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

/**
 * Created by jiyun on 2017/2/5.
 */
@Controller
@RequestMapping("/admin/article")
public class AdminArticleController extends BaseController {
    private static Logger logger = LoggerFactory.getLogger(AdminArticleController.class);
    // 文章添加页面
    private static String addArticlePage = getViewPath("/admin/article/article-add");
    // 文章列表
    private static String articleListPage = getViewPath("/admin/article/article-list");

    @Autowired
    private ArticleService articleService;

    @InitBinder({"articleContent"})
    public void initArticleContentBinder(WebDataBinder binder) {
        binder.setFieldDefaultPrefix("articleContent.");
    }

    @InitBinder({"article"})
    public void initArticleBinder(WebDataBinder binder) {
        binder.setFieldDefaultPrefix("article.");
    }

    @InitBinder({"queryArticle"})
    public void initQueryArticleBinder(WebDataBinder binder) {
        binder.setFieldDefaultPrefix("queryArticle.");
    }

    /**
     * 执行添加文章
     */
    @RequestMapping("/addArticle")
    @ResponseBody
    public String addArticle(HttpServletRequest request) {
        JsonObject resultJson = new JsonObject();
        try {
            String articleTypeString = request.getParameter("articleType");
            String clickNumString = request.getParameter("clickNum");
            String statusString = request.getParameter("status");
            //数据验证
            if (!WebUtils.isValidateRealString(articleTypeString, clickNumString, statusString)
                    || !WebUtils.isNumeric(articleTypeString, clickNumString, statusString)){
                resultJson.addProperty("status", 400);
                resultJson.addProperty("msg", "数据输入不合法！");
                return gson.toJson(resultJson);
            }
            //提取表单信息
            Article article = new Article();
            ArticleContent articleContent = new ArticleContent();
            article.setTitle(request.getParameter("title"));
            article.setKeyWord(request.getParameter("keyWord"));
            article.setImageUrl(request.getParameter("imageUrl"));
            article.setArticleType(Integer.valueOf(articleTypeString));
            articleContent.setContent(request.getParameter("content"));
            article.setPublishTime(WebUtils.stringToTimestamp(request.getParameter("publishTime")));
            article.setClickNum(Integer.valueOf(clickNumString));
            article.setStatus(Integer.valueOf(statusString));
            article.setCreateTime(new Timestamp(new Date().getTime()));
            article.setArticleContent(articleContent);
            articleContent.setArticleId(article.getArticleId());
            //保存文章
            articleService.createArticle(article);
            //返回json数据
            resultJson.addProperty("status", 200);
            resultJson.addProperty("msg", "添加成功");
            resultJson.addProperty("url", "/admin/article/initArticleList");
        } catch (Exception e) {
            logger.error("AdminArticleController.addArticle()---error", e);
            resultJson.addProperty("status", 400);
            resultJson.addProperty("msg", "添加失败！");
        }
        logger.info(gson.toJson(resultJson));
        return gson.toJson(resultJson);
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @ResponseBody
    public String delete(HttpServletRequest request) {
        JsonObject resultJson = new JsonObject();
        try {
            String[] articleIds = request.getParameter("articleId").split(",");
            if (articleIds != null && articleIds.length > 0) {
                articleService.deleteArticleByIds(articleIds);
            }
            resultJson.addProperty("status", 200);
            resultJson.addProperty("msg", "删除成功");
            resultJson.addProperty("url", "reload");
        } catch (Exception e) {
            logger.error("AdminArticleController.delete()--error", e);
            resultJson.addProperty("status", 400);
            resultJson.addProperty("msg", "删除失败！");
        }
        logger.info(gson.toJson(resultJson));
        return gson.toJson(resultJson);
    }

    /**
     * 分页查询文章列表
     */
    @RequestMapping("/getArticleList")
    @ResponseBody
    public String getArticleList(HttpServletRequest request) {
        JsonObject resultJson = new JsonObject();
        try {
            QueryArticle queryArticle = new QueryArticle();
            String articleTypeString = request.getParameter("articleType");
            String pageNoString = request.getParameter("pageNo");
            if (!WebUtils.isValidateRealString(pageNoString) || !WebUtils.isNumeric(pageNoString)) {
                resultJson.addProperty("status", 400);
                resultJson.addProperty("msg", "数据输入不合法！");
                return gson.toJson(resultJson);
            }
            if (WebUtils.isValidateRealString(articleTypeString) && WebUtils.isNumeric(articleTypeString)) {
                queryArticle.setType(Integer.valueOf(articleTypeString));
            }
            queryArticle.setQueryKey(request.getParameter("keyword"));
            queryArticle.setBeginCreateTime(WebUtils.stringToData(request.getParameter("start_date")));
            queryArticle.setEndCreateTime(WebUtils.stringToData(request.getParameter("end_date")));
            PageModel<Article> page = new PageModel<>();
            page.setPageSize(8);
            page.setPageNo(Integer.valueOf(pageNoString));
            List<Article> articleList = articleService.queryArticlePage(queryArticle, page);
            JsonArray array = new JsonArray();
            for (Article article : articleList) {
                JsonObject list = new JsonObject();
                list.addProperty("articleId", article.getArticleId());
                list.addProperty("title", article.getTitle());
                list.addProperty("keyWord", article.getKeyWord());
                list.addProperty("articleType", article.getArticleType());
                list.addProperty("createTime", WebUtils.timestampToString(article.getCreateTime()));
                list.addProperty("publishTime", WebUtils.timestampToString(article.getPublishTime()));
                list.addProperty("status", article.getStatus());
                list.addProperty("imageUrl", article.getImageUrl());
                list.addProperty("clickNum", article.getClickNum());
                list.addProperty("sort", article.getStatus());
                list.addProperty("content", articleService.queryArticleContentByArticleId(article.getArticleId()));
                array.add(list);
            }
            JsonObject list = new JsonObject();
            list.add("list", array);
            resultJson.addProperty("status", 200);
            resultJson.addProperty("pages", page.getTotalPageSize());
            resultJson.add("data", list);
        } catch (Exception e) {
            logger.error("AdminArticleController.showArticleList()--error", e);
            resultJson.addProperty("status", 400);
            resultJson.addProperty("msg", "获取列表失败！");
        }
        logger.info(gson.toJson(resultJson));
        return gson.toJson(resultJson);
    }

    /**
     * 修改文章
     */
    @RequestMapping("/updateArticle")
    @ResponseBody
    public String updateArticle(HttpServletRequest request) {
        JsonObject resultJson = new JsonObject();
        try {
            String articleIdString = request.getParameter("articleId");
            String articleTypeString = request.getParameter("articleType");
            String clickNumString = request.getParameter("clickNum");
            String statusString = request.getParameter("status");
            //数据验证
            if (!WebUtils.isValidateRealString(articleIdString, articleTypeString, clickNumString, statusString)
                    || !WebUtils.isNumeric(articleIdString, articleTypeString, clickNumString, statusString)){
                resultJson.addProperty("status", 400);
                resultJson.addProperty("msg", "数据输入不合法！");
                return gson.toJson(resultJson);
            }
            Article article = articleService.queryArticleById(Integer.valueOf(articleIdString));
            ArticleContent articleContent = article.getArticleContent();
            article.setTitle(request.getParameter("title"));
            article.setKeyWord(request.getParameter("keyWord"));
            article.setImageUrl(request.getParameter("imageUrl"));
            article.setArticleType(Integer.valueOf(articleTypeString));
            articleContent.setContent(request.getParameter("content"));
            article.setPublishTime(WebUtils.stringToTimestamp(request.getParameter("publishTime")));
            article.setClickNum(Integer.valueOf(clickNumString));
            article.setStatus(Integer.valueOf(statusString));

            articleService.updateArticleContent(articleContent);
            articleService.updateArticle(article);
            // 修改成功返回原列表页面
            resultJson.addProperty("status", 200);
            resultJson.addProperty("url", "reload");
            resultJson.addProperty("msg", "更新成功");
        } catch (Exception e) {
            logger.error("AdminArticleController.updateArticle()--error", e);
            resultJson.addProperty("status", 400);
            resultJson.addProperty("msg", "更新失败！");
        }
        logger.info(gson.toJson(resultJson));
        return gson.toJson(resultJson);
    }

    @RequestMapping("updateStatus")
    @ResponseBody
    public String updateStatus(HttpServletRequest request) {
        JsonObject resultJson = new JsonObject();
        try {
            int articleId = Integer.valueOf(request.getParameter("articleId"));
            int status = request.getParameter("status").equals("false") ? 0 : 1;
            Article article = articleService.queryArticleById(articleId);
            article.setStatus(status);
            articleService.updateArticle(article);
            resultJson.addProperty("status", 200);
            resultJson.addProperty("msg", "更新成功");
        } catch (Exception e) {
            logger.error("UserController.updateStatus()--error", e);
            resultJson.addProperty("status", 400);
            resultJson.addProperty("msg", "更新失败！");
        }
        logger.info(gson.toJson(resultJson));
        return gson.toJson(resultJson);
    }

    /**
     * 初始化文章添加页面
     */
    @RequestMapping("/initAddArticle")
    public ModelAndView initAddArticle() {
        ModelAndView model = new ModelAndView();
        model.setViewName(addArticlePage);
        return model;
    }

    @RequestMapping("/initArticleList")
    public ModelAndView initArticleList() {
        ModelAndView model = new ModelAndView();
        model.setViewName(articleListPage);
        return model;
    }

}
